package com.njupt.yanglonglong.report.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.njupt.yanglonglong.report.demo.common.Result;
import com.njupt.yanglonglong.report.demo.dto.CourseTeacherInfoDto;
import com.njupt.yanglonglong.report.demo.entity.Course;
import com.njupt.yanglonglong.report.demo.entity.RCourseTeacher;
import com.njupt.yanglonglong.report.demo.entity.RUser;
import com.njupt.yanglonglong.report.demo.service.RCourseTeacherService;
import com.njupt.yanglonglong.report.demo.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @className: RCourseTeacherController
 * @Description: 课程老师表相关
 * @author: lpl
 * @date: 2021/4/27 22:03
 */
@Slf4j
@RestController
@CrossOrigin
public class RCourseTeacherController {

    @Autowired
    RCourseTeacherService rCourseTeacherService;

    @Autowired
    RedisUtil redisUtil;

    /**
     * 根据老师id查询已经选择的课程
     *
     * @param request
     * @return
     */
    @RequestMapping("/queryTeacherCourseList")
    public Result<JSONObject> queryTeacherCourseList(HttpServletRequest request) {
        JSONObject res = new JSONObject();
        String token = request.getHeader("Authorization");
        RUser user = redisUtil.getUser(token);
        log.info("接口/queryTeacherCourseList接收到的数据为：" + user);
        List<Course> courseList = rCourseTeacherService.getTeacherCourse(user.getUserId());
        log.info(user + "查询到的课程为" + courseList);
        if (courseList.size() == 0) {
            res.put("msg", "您没有选择课程");
            return Result.error(res);
        }
        res.put("data", courseList);
        return Result.success(res);
    }


    /**
     * 批量提交某个老师选择的课程，直接在数据库中添加含有teacherid的数据(操作小表格)
     *
     * @param courses courseList
     * @param request teacherId
     * @return isSuccess
     */
    @PostMapping("/addCourseTeacherList")
    public Result<JSONObject> addCourseTeacherList(@RequestBody List<Course> courses, HttpServletRequest request) {
        JSONObject res = new JSONObject();

        log.info("接口/addCourseTeacher接收到的数据为：" + courses.toString());
        String token = request.getHeader("Authorization");
        RUser user = redisUtil.getUser(token);
        List<RCourseTeacher> rCourseTeacherList = new ArrayList<>();
        //整理数据到实体List中
        for (int i = 0; i < courses.size(); i++) {
            rCourseTeacherList.add(new RCourseTeacher());
            rCourseTeacherList.get(i).setCourse_id(courses.get(i).getCourseId());
            rCourseTeacherList.get(i).setTeacher_id(user.getUserId());
        }
        boolean save = rCourseTeacherService.saveBatch(rCourseTeacherList);
        if (!save) {
            res.put("msg", "添加课程失败，请检查是否已经添加");
            log.error("/addCourseTeacher添加课程失败，请检查是否已经添加");
            return Result.error(res);
        }
        res.put("msg", "添加成功");
        return Result.success(res);
    }

    /**
     * 提交某个老师选择的课程,接收courseId
     *
     * @param map
     * @param request
     * @return
     */
    @PostMapping("/addCourseTeacher")
    public Result<JSONObject> addCourseTeacher(@RequestBody HashMap<String, String> map, HttpServletRequest request) {
        JSONObject res = new JSONObject();

        log.info("接口/addCourseTeacher接收到的数据为：" + map);
        String token = request.getHeader("Authorization");
        RUser user = redisUtil.getUser(token);
        RCourseTeacher rCourseTeacher = new RCourseTeacher();

        //整理数据到实体List中
        rCourseTeacher.setCourse_id(map.get("courseId"));
        rCourseTeacher.setTeacher_id(user.getUserId());
        rCourseTeacher.setStartTime(map.get("startTime"));
        rCourseTeacher.setEndTime(map.get("endTime"));

        try {
            rCourseTeacherService.save(rCourseTeacher);
        } catch (Exception e) {
            e.printStackTrace();
            res.put("msg", "添加课程失败，请检查是否已经存在");
            log.error("/addCourseTeacher添加课程失败，请检查是否已经存在");
            return Result.error(res);
        }
        res.put("msg", "添加成功");
        return Result.success(res);
    }

    /**
     * 根据teacherid以及courseid删除数据
     *
     * @param request
     * @param map
     * @return
     */
    @PostMapping("/deleteByTCId")
    public Result<JSONObject> deleteByTCId(HttpServletRequest request, @RequestBody HashMap<String, String> map) {

        String courseId = map.get("courseId");
        log.info("接口/deleteByTCId接收到的数据为：courseId" + courseId);
        String token = request.getHeader("Authorization");
        RUser user = redisUtil.getUser(token);
        RCourseTeacher rCourseTeacher = new RCourseTeacher();
        //根据courseid和userid查询表格
        rCourseTeacher.setCourse_id(courseId);
        rCourseTeacher.setTeacher_id(user.getUserId());
        int delete = rCourseTeacherService.deleteByTCId(rCourseTeacher);

        JSONObject res = new JSONObject();
        if (delete <= 0) {
            log.error("/deleteByTCId删除失败" + courseId + user.getUserId());
            res.put("msg", "删除失败");
            return Result.error(res);
        }
        res.put("msg", "删除成功");
        return Result.success(res);
    }

    /**
     * 学生端获得可选课程的信息
     *
     * @return
     */
    @RequestMapping("/queryOpenedCourses")
    public Result<JSONObject> queryOpenedCourses(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        RUser user = redisUtil.getUser(token);

        List<CourseTeacherInfoDto> courseTeacherInfoDtos = rCourseTeacherService.queryOpenedCourses(user.getUserId());
        JSONObject res = new JSONObject();

        log.info("/queryOpenedCourses接收请求,user {}", user);
        if (courseTeacherInfoDtos.isEmpty()) {
            res.put("msg", "目前没有开设课程");
            return Result.error(res);
        }

        log.info("/queryOpenedCourses返回查询 data:" + courseTeacherInfoDtos);
        res.put("data", courseTeacherInfoDtos);
        return Result.success(res);
    }

    /**
     * 获取Teacher选择的课程
     *
     * @param request
     * @return
     */
    @PostMapping("/getTeacherCourse")
    public Result<JSONObject> getTeacherCourse(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        RUser user = redisUtil.getUser(token);
        log.info("/getTeacherCourse接收到请求，User" + user);

        List<Course> teacherCourse = rCourseTeacherService.getTeacherCourse(user.getUserId());
        JSONObject res = new JSONObject();
        if (teacherCourse.isEmpty()) {
            res.put("msg", "获得您的课程失败，请检查是否添加或联系管理员");
            log.error("获取课程失败");
            return Result.error(res);
        }
        res.put("data", teacherCourse);
        return Result.success(res);
    }

    /**
     * 老师端更新时间,需要start_time、end_time、course_id、(user_id)
     *
     * @param request
     * @param map
     * @return
     */
    @PostMapping("/updateTeacherCourseTime")
    public Result<JSONObject> updateTeacherCourseTime(HttpServletRequest request, @RequestBody HashMap<String, String> map) {
        String token = request.getHeader("Authorization");
        RUser user = redisUtil.getUser(token);

        log.info("/updateTeacherCourseTime接收到请求:" + user + "  " + map);

        JSONObject res = new JSONObject();
        String startTime = map.get("startTime");
        String endTime = map.get("endTime");
        RCourseTeacher rCourseTeacher = new RCourseTeacher();
        String courseId = map.get("courseId");
        String teacherId = user.getUserId();

        rCourseTeacher.setCourse_id(courseId);
        rCourseTeacher.setTeacher_id(teacherId);
        rCourseTeacher.setStartTime(startTime);
        rCourseTeacher.setEndTime(endTime);

        boolean update = rCourseTeacherService.updateByCourseIdTeacherId(rCourseTeacher);

        if (!update) {
            res.put("msg", "更新时间失败");
            log.error("/updateTeacherCourseTime更新数据库失败，接口数据为：" + teacherId + " " + map);

            return Result.error(res);
        }

        res.put("msg", "更改开课时间成功");
        return Result.success(res);
    }


}
